package com.wangtao.firstapp.fragments.communityfragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.picasso.Picasso;
import com.wangtao.firstapp.R;
import com.wangtao.firstapp.activity.ArticleDetails;
import com.wangtao.firstapp.activity.ArticleGuidePicture;
import com.wangtao.firstapp.activity.MyFollowsActivity;
import com.wangtao.firstapp.activity.NewestActivity;
import com.wangtao.firstapp.adapters.ArticleGuideAdapter;
import com.wangtao.firstapp.adapters.RecyclerViewAdapter;
import com.wangtao.firstapp.inter.OnRVItemClickListener;
import com.wangtao.firstapp.inter.OnRVItemLongClickListener;
import com.wangtao.firstapp.modles.ArticleDetailsData;
import com.wangtao.firstapp.modles.ArticleGuide;
import com.wangtao.firstapp.modles.CommunityArticlesData;
import com.wangtao.firstapp.utils.HttpUtils;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章页面
 * <p/>
 * Created by lanouhn on 16/8/24.
 */
public class CommunityArticleFragment extends Fragment implements OnRVItemClickListener, OnRVItemLongClickListener {
    private List<CommunityArticlesData.DataBean.TopicBean> articlesdata = new ArrayList<>();// 适配器需要的数据的实体类
    private List<CommunityArticlesData.DataBean.TopicBean> datas = new ArrayList<>();
    private RecyclerViewAdapter rva;// RecyclerViewAdapter的适配器
    private XRecyclerView xrecyclerview_article;// RecyclerView
    private ScrollView scrollview_article;
    private ImageView imageview_articleguide;
    private String result_pic;
    private ArticleGuide articleGuide;// 原创文章指南图片的实体类
    private ArticleGuideAdapter articleGuideAdapter;// 原创文章指南图片适配器
    private SwipeRefreshLayout swiperefreshlayout_fragment;// 下拉刷新的控件
    private RadioButton rb_topic_community_attention, rb_topic_community_newest, rb_topic_community_rank;
    private int page = 0;
    private LinearLayoutManager llm;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.communityarticlefragment, null);
        xrecyclerview_article = (XRecyclerView) view.findViewById(R.id.xrecyclerview_article);
        scrollview_article = (ScrollView) view.findViewById(R.id.scrollview_article);
        imageview_articleguide = (ImageView) view.findViewById(R.id.imageview_articleguide);
        // swiperefreshlayout_fragment = (SwipeRefreshLayout) view.findViewById(R.id.swiperefreshlayout_fragment);
        Picasso.with(getContext()).load(R.mipmap.articleguide).config(Bitmap.Config.RGB_565).into(imageview_articleguide);
        xrecyclerview_article.setFocusable(false);
        rb_topic_community_attention = (RadioButton) view.findViewById(R.id.rb_topic_community_attention);// 文章列表下关注动态按钮
        rb_topic_community_newest = (RadioButton) view.findViewById(R.id.rb_topic_community_newest);// 文章列表下新鲜原创按钮
        rb_topic_community_rank = (RadioButton) view.findViewById(R.id.rb_topic_community_rank);// 文章列表下排行榜

        llm = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        xrecyclerview_article.setLayoutManager(llm);// 设置布局管理器


        xrecyclerview_article.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xrecyclerview_article.setArrowImageView(R.drawable.ic_loading_rotate);
        xrecyclerview_article.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 0;
                getArticlesData();
            }

            @Override
            public void onLoadMore() {
                page++;
                getArticlesData();
            }
        });

        initEvent();
        getArticlesData();
        // SwipeToRefresh();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initEvent();
    }

    private void initEvent() {
        // 原创文章指南 图片点击事件
        imageview_articleguide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_guidepicture = new Intent(getActivity(), ArticleGuidePicture.class);
                String url = "http://m.bantangapp.com/guide2.html";
                intent_guidepicture.putExtra("url", url);
                startActivity(intent_guidepicture);
            }
        });
        rb_topic_community_attention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_attention = new Intent(getActivity(), MyFollowsActivity.class);
                startActivity(intent_attention);
            }
        });
        rb_topic_community_newest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_newest = new Intent(getActivity(), NewestActivity.class);
                startActivity(intent_newest);
            }
        });
        // 排行榜
        //rb_topic_community_rank.setOnClickListener();
    }

    // 加载文章详情
    private void getArticlesData() {
        try {
            String url = "http://open4.bantangapp.com/topics/topic/listByUsers";
            String params = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2559956&oauth_token=6beffa8c92276d19d3c23acb596024e6&track_deviceid=866962021116243&track_device_info=m1+note&channel_name=ppzhushuo&app_installtime=1471923362&app_versions=5.8.6&os_versions=5.1&screensize=1080&v=18&page=" + page + "&pagesize=20&sort_type=1";

            HttpUtils.doPostAsyn(url, params, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson_articlesdata = new Gson();
                    datas = gson_articlesdata.fromJson(result, CommunityArticlesData.class).getData().getTopic();
                    if (datas.size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 加载原创文章指南图片
        String url1 = "http://open4.bantangapp.com/community/post/article";
        String params1 = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2560255&oauth_token=4df22230db195bba652ef0e593881122&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18";
        try {
            HttpUtils.doPostAsyn(url1, params1, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson1 = new Gson();
                    articleGuide = gson1.fromJson(result, ArticleGuide.class);
                    if (articleGuide.getData().getInsert_element().size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    // Toast.makeText(getActivity(), "网络访问失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    if (page == 0) {
                        articlesdata.clear();
                        articlesdata.addAll(datas);
                        rva = new RecyclerViewAdapter(getActivity(), articlesdata);// 初始化适配器
                        xrecyclerview_article.setAdapter(rva);// 给RecyclerView设置适配器
                        xrecyclerview_article.refreshComplete();
                        datas.clear();
                    } else {
                        articlesdata.addAll(datas);
                        rva.notifyDataSetChanged();
                        xrecyclerview_article.loadMoreComplete();
                        datas.clear();
                    }
                    rva.setClickListener(CommunityArticleFragment.this);// Fragment中使用回调接口
                    rva.setLongClickListener(CommunityArticleFragment.this);// Fragment中使用回调接口
                    break;
                case 2:
                    Picasso.with(getActivity()).load(articleGuide.getData().getInsert_element().get(0).getPhoto()).into(imageview_articleguide);
                    break;
            }
        }
    };

    @Override
    public void OnRVItemClickListener(int position) {
        // 图文详情的网址
        // 图文详情的ID
        String id = articlesdata.get(position).getId();
//        String address = "http://open4.bantangapp.com/topic/newInfo";
//        String parameter = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508" +
//                "&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18&id=" + articlesdata.getData().getTopic().get(position).getId() + "&trace_id=&relate_pid=&statistics_uv=1&is_night=0";
        // 大家都在看 的网址
//        String address1 = "http://open4.bantangapp.com/topics/topic/relationRec";
//        String parameter1 = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508" +
//                "&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18&id=" + articlesdata.getData().getTopic().get(position).getId();
        // 评论  网址
//        String address2 = "http://open4.bantangapp.com/topics/comment/list";
//        String parameter2 = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508" +
//                "&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18&page=1&pagesize=20&id=" + articlesdata.getData().getTopic().get(position).getId();
        Intent intent_click = new Intent(getActivity(), ArticleDetails.class);
        intent_click.putExtra("id", id);
//        intent_click.putExtra("url1", address1);
//        intent_click.putExtra("url2", address2);
//        intent_click.putExtra("param", parameter);
//        intent_click.putExtra("param1", parameter1);
//        intent_click.putExtra("param2", parameter2);
        startActivity(intent_click);
    }

    @Override
    public void OnRVItemLongClickListener(int position) {
        // 图文详情的网址
        // String address = "http://open4.bantangapp.com/topic/newInfo";
        // String parameter = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508" +
        //         "&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18&id=" + articlesdata.getData().getTopic().get(position).getId() + "&trace_id=&relate_pid=&statistics_uv=1&is_night=0";
        // 大家都在看 的网址
        // String address1 = "http://open4.bantangapp.com/topics/topic/relationRec";
        // String parameter1 = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508" +
        //         "&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18&id=" + articlesdata.getData().getTopic().get(position).getId();
        // 评论  网址
        // String address2 = "http://open4.bantangapp.com/topics/comment/list";
        // String parameter2 = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508" +
        //        "&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18&page=0&pagesize=20&id=" + articlesdata.getData().getTopic().get(position).getId();
        String id = articlesdata.get(position).getId();
        Intent intent_longclick = new Intent(getActivity(), ArticleDetails.class);
        intent_longclick.putExtra("id", id);
//        intent_longclick.putExtra("url1", address1);
//        intent_longclick.putExtra("url2", address2);
//        intent_longclick.putExtra("param", parameter);
//        intent_longclick.putExtra("param1", parameter1);
//        intent_longclick.putExtra("param2", parameter2);
        startActivity(intent_longclick);
    }

    // 下拉刷新
    private void SwipeToRefresh() {
        swiperefreshlayout_fragment.setColorSchemeColors(Color.CYAN, Color.BLUE, Color.GREEN, Color.YELLOW);
        swiperefreshlayout_fragment.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swiperefreshlayout_fragment.setRefreshing(true);
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swiperefreshlayout_fragment.setRefreshing(false);
                        getArticlesData();
                        rva.notifyDataSetChanged();
                    }
                }, 3000);
            }
        });
    }


}
